package com.longcai.service.impl.nearbyshop;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.longcai.advice.RollBackExecption;
import com.longcai.bean.ApiResult;
import com.longcai.constants.BaseConstants;
import com.longcai.entity.nearby.ClyjNearbyGoodsType;
import com.longcai.entity.nearby.ClyjNearbyPackage;
import com.longcai.entity.nearby.ClyjNearbyShops;
import com.longcai.entity.nearby.ClyjNearbyShopsGoods;
import com.longcai.entity.nearby.ClyjNearbyShopsGoodsSpec;
import com.longcai.entity.nearby.vo.ClyjNearbyShopsGoodsQueryVo;
import com.longcai.entity.nearby.vo.ClyjNearbyGoodsTypeVo;
import com.longcai.mapper.ClyjNearbyShopsMapper;
import com.longcai.mapper.nearbyshop.ClyjNearbyGoodsTypeMapper;
import com.longcai.mapper.nearbyshop.ClyjNearbyShopsGoodsMapper;
import com.longcai.mapper.nearbyshop.ClyjNearbyShopsGoodsSpecMapper;
import com.longcai.page.table.PageTableResponse;
import com.longcai.service.nearbyshop.ClyjNearbyShopsGoodsService;
import com.longcai.util.LoginUser;
import com.longcai.util.OSSUtils;
import com.longcai.util.StringUtils;
import com.longcai.util.UserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 附近-商铺商品 服务实现类
 * </p>
 *
 * @author M
 * @since 2019-04-12
 */
@Service
public class ClyjNearbyShopsGoodsServiceImpl extends ServiceImpl<ClyjNearbyShopsGoodsMapper, ClyjNearbyShopsGoods>
		implements ClyjNearbyShopsGoodsService {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private ClyjNearbyShopsGoodsMapper clyjNearbyShopsGoodsMapper;

	@Autowired
	private ClyjNearbyShopsMapper clyjNearbyShopsMapper;
	@Autowired
	private ClyjNearbyGoodsTypeMapper clyjNearbyGoodsTypeMapper;

	@Autowired
	private ClyjNearbyShopsGoodsSpecMapper clyjNearbyShopsGoodsSpecMapper;

	/****
	 * 查询外送 商品列表
	 */
	@Override
	public PageTableResponse queryShopsGoodsList(ClyjNearbyShopsGoodsQueryVo clyjNearbyShopsGoodsQueryVo, Integer start,
			Integer length) {
		// 查询登录用户角色
		LoginUser loginUser = UserUtil.getLoginUser();
		QueryWrapper<ClyjNearbyShopsGoods> q = assemblingParam(clyjNearbyShopsGoodsQueryVo, loginUser);
		if (q == null) {
			return null;
		}
		// 分页
		Page<ClyjNearbyShopsGoods> page = new Page<ClyjNearbyShopsGoods>(start, length);
		IPage<ClyjNearbyShopsGoods> shopsGoodsIPage = this.clyjNearbyShopsGoodsMapper.selectPage(page, q);
		List<ClyjNearbyShopsGoods> records = shopsGoodsIPage.getRecords();
		for (ClyjNearbyShopsGoods clyjNearbyShopsGoods : records) {
			String goodsTypeId = clyjNearbyShopsGoods.getGoodsTypeId();
			QueryWrapper<ClyjNearbyGoodsType> queryClyjNearbyGoodsType = new QueryWrapper<ClyjNearbyGoodsType>();
			queryClyjNearbyGoodsType.eq("id", goodsTypeId);
			ClyjNearbyGoodsType clyjNearbyGoodsType = clyjNearbyGoodsTypeMapper.selectOne(queryClyjNearbyGoodsType);
			/** 查询是商品类型名称 **/
			clyjNearbyShopsGoods.setGoodsTypeName(clyjNearbyGoodsType.getName());
			QueryWrapper<ClyjNearbyShopsGoodsSpec> queryClyjNearbyShopsGoodsSpec = new QueryWrapper<ClyjNearbyShopsGoodsSpec>();
			queryClyjNearbyShopsGoodsSpec.eq("goods_id", clyjNearbyShopsGoods.getGoodsId());
			/** 查询商品明细实体列表 **/
			List<ClyjNearbyShopsGoodsSpec> clyjNearbyShopsGoodsSpecList = clyjNearbyShopsGoodsSpecMapper
					.selectList(queryClyjNearbyShopsGoodsSpec);
			clyjNearbyShopsGoods.setClyjNearbyShopsGoodsSpecList(clyjNearbyShopsGoodsSpecList);
		}
		shopsGoodsIPage.setRecords(records);
		PageTableResponse pageTableResponse = new PageTableResponse(shopsGoodsIPage.getTotal(),
				shopsGoodsIPage.getTotal(), shopsGoodsIPage.getRecords());
		return pageTableResponse;
	}

	/**
	 * 外卖商品列表 查询条件组装
	 **/
	public QueryWrapper<ClyjNearbyShopsGoods> assemblingParam(ClyjNearbyShopsGoodsQueryVo clyjNearbyShopsGoodsQueryVo,
			LoginUser loginUser) {
		ClyjNearbyShops clyjNearbyShops = queryClyjNearbyShops();
		if (clyjNearbyShops == null) {
			logger.error("查询店铺失败-----------------参数非法" + "mich_id" + UserUtil.getLoginUser().getUserId());
			return null;
		}
		QueryWrapper<ClyjNearbyShopsGoods> queryClyjNearbyShopsGoods = new QueryWrapper<ClyjNearbyShopsGoods>();
		queryClyjNearbyShopsGoods.eq("shops_id", clyjNearbyShops.getShopsId());
		if (clyjNearbyShopsGoodsQueryVo != null) {
			String type = clyjNearbyShopsGoodsQueryVo.getType();
			if (StringUtils.isEmpty(type)) {
				logger.error("查询外卖商品列表-----------------参数非法" + "type" + type);
				return null;
			}
			/****
			 * 查询类型(0,销售中 ，1未审核 ，2，库存警告 3，仓库中 4.回收站-根据删除标示判断)
			 */
			switch (type) {
			case BaseConstants.TYPE_SALE_ING:
				queryClyjNearbyShopsGoods.eq("status", BaseConstants.PUT_ON_SALE);
				// '审核状态（0，已审核，1未审核）先审核后才能上下架'
				queryClyjNearbyShopsGoods.eq("auditing_status", BaseConstants.AUDITING_STATUS_0);
				queryClyjNearbyShopsGoods.eq("delete_flg", BaseConstants.DELETE_FLG_1);
				break;
			case BaseConstants.TYPE_NOT_AUDITING:
				// '审核状态（0，已审核，1未审核）先审核后才能上下架'
				queryClyjNearbyShopsGoods.eq("auditing_status", BaseConstants.AUDITING_STATUS_1);
				queryClyjNearbyShopsGoods.eq("delete_flg", BaseConstants.DELETE_FLG_1);
				break;
			case BaseConstants.TYPE_STOCK_WARNING:
				queryClyjNearbyShopsGoods.eq("status", BaseConstants.PUT_ON_SALE);
				// '审核状态（0，已审核，1未审核）先审核后才能上下架'
				queryClyjNearbyShopsGoods.eq("auditing_status", BaseConstants.AUDITING_STATUS_0);
				queryClyjNearbyShopsGoods.eq("delete_flg", BaseConstants.DELETE_FLG_1);
				List<ClyjNearbyShopsGoodsSpec> list = clyjNearbyShopsGoodsSpecMapper.compareStock();
				if (list != null && list.size() > 0) {
					List<String> listStr = new ArrayList<>();
					for (ClyjNearbyShopsGoodsSpec clyjNearbyShopsGoodsSpec : list) {
						listStr.add(clyjNearbyShopsGoodsSpec.getGoodsId());
					}
					queryClyjNearbyShopsGoods.in("goods_id", listStr);
				}else{//证明规格未设置---则查询商品表中库存为0 的数据
					List<ClyjNearbyShopsGoods> listGoods = clyjNearbyShopsGoodsMapper.compareStock();	
					List<String> listStr = new ArrayList<>();
					for (ClyjNearbyShopsGoods clyjNearbyShopsGoods : listGoods) {
						listStr.add(clyjNearbyShopsGoods.getGoodsId());
					}
					queryClyjNearbyShopsGoods.in("goods_id", listStr);
				}
				break;
			case BaseConstants.TYPE_WAREHOUSE:
				List<ClyjNearbyShopsGoodsSpec> lists = clyjNearbyShopsGoodsSpecMapper.queryStock();
				if (lists != null && lists.size() > 0) {
					List<String> listStr = new ArrayList<>();
					for (ClyjNearbyShopsGoodsSpec clyjNearbyShopsGoodsSpec : lists) {
						listStr.add(clyjNearbyShopsGoodsSpec.getGoodsId());
					}
					queryClyjNearbyShopsGoods.in("goods_id", listStr).or().eq("status", BaseConstants.PULL_OFF_SHELVES);
				}else{
					List<ClyjNearbyShopsGoods> listss = clyjNearbyShopsGoodsMapper.queryStock();
					if (listss != null && listss.size() > 0) {
						List<String> listStr = new ArrayList<>();
						for (ClyjNearbyShopsGoods clyjNearbyShopsGoods : listss) {
							listStr.add(clyjNearbyShopsGoods.getGoodsId());
						}
						queryClyjNearbyShopsGoods.in("goods_id", listStr).or().eq("status", BaseConstants.PULL_OFF_SHELVES);
			    	}
				}
				break;
			case BaseConstants.TYPE_WASTE_MATERIALS:
				queryClyjNearbyShopsGoods.eq("delete_flg", BaseConstants.DELETE_FLG_0);
				break;
			default:
				System.out.println("default");
				break;
			}
			if (StringUtils.isNotEmpty(clyjNearbyShopsGoodsQueryVo.getGoodsName())) {// 商品
				queryClyjNearbyShopsGoods.like("goods_name", clyjNearbyShopsGoodsQueryVo.getGoodsName());
			}
			if (StringUtils.isNotEmpty(clyjNearbyShopsGoodsQueryVo.getGoodsTypeId())) {
				queryClyjNearbyShopsGoods.eq("goods_type_id", clyjNearbyShopsGoodsQueryVo.getGoodsTypeId());
			}

		}
		return queryClyjNearbyShopsGoods;
	}

	/****
	 * 查询 外送商品列表 选项卡 的数量
	 * 
	 * @return
	 */
	@Override
	public Map<String, Integer> queryShopsGoodsMode() {
		Map<String, Integer> map = new HashMap<>();
		/**
		 * 查询销售中数量
		 **/
		int a = clyjNearbyShopsGoodsMapper.querySaleIngCount();
		/**
		 * 查询未审核的数量
		 **/
		int b = clyjNearbyShopsGoodsMapper.querynotAuditing();
		/****
		 * 库存低于库存警告数量
		 */
		int c = clyjNearbyShopsGoodsSpecMapper.queryStockCount();
		/**
		 * 仓库中的数量
		 **/
		int d = clyjNearbyShopsGoodsSpecMapper.queryStockSpecCount();
		/**
		 * 查询回收站
		 **/
		int e = clyjNearbyShopsGoodsMapper.queryDeleteCount();
		map.put("saleIng", a);
		map.put("notAuditing", b);
		map.put("stockWarning", c);
		map.put("warehouse", d);
		map.put("wasteMaterials", e);
		return map;
	}

	/****
	 * 外送商品列表 下架单个
	 * 
	 * @param list
	 * @return
	 * @throws RollBackExecption 
	 */
	@Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ApiResult<?> pullOffShelves(String goodsId) throws RollBackExecption {
		if (StringUtils.isEmpty(goodsId)) {
			return ApiResult.fail("参数非法，下架商品Id不能为空");
		}
		try {
			int i = clyjNearbyShopsGoodsMapper.pullOffShelvesBatch(goodsId);
			if (i == 0) {
				int a=1/i;
			}
		} catch (Exception e) {
			throw new RollBackExecption("下架外送商品失败");
		}
		return ApiResult.success();
	}

	/****
     * 外送商品列表
     * 删除单个
     * @param list
     * @return
	 * @throws RollBackExecption 
     */
	@Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ApiResult<?> deleteNearbyShopsGoods(String goodsId) throws RollBackExecption {
		if(StringUtils.isEmpty(goodsId)){
			return	ApiResult.fail("参数非法，删除商品Id不能为空");
		}
		try {
			QueryWrapper<ClyjNearbyShopsGoods> query=new QueryWrapper<ClyjNearbyShopsGoods>();
			query.eq("goods_id", goodsId);
			int i=clyjNearbyShopsGoodsMapper.delete(query);
			QueryWrapper<ClyjNearbyShopsGoodsSpec> queryWrapper=new QueryWrapper<ClyjNearbyShopsGoodsSpec>();
			queryWrapper.eq("goods_id", goodsId);
			int j=clyjNearbyShopsGoodsSpecMapper.delete(queryWrapper);
			if(j==0||i==0){
				int a=1/0;
			}
			} catch (Exception e) {
				throw new RollBackExecption("删除外送商品失败");
			}
		return ApiResult.success();
	}

	/****
	 * 外送商品列表 批量下架
	 * 
	 * @param list
	 * @return
	 * @throws RollBackExecption 
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ApiResult<?> batchPullOffShelves(List<Map<String, String>>  list) throws RollBackExecption {
		if (list == null || list.size() < 1) {
			return ApiResult.fail("参数非法，批量下架Id不能为空");
		}
		try {
			int i=	clyjNearbyShopsGoodsMapper.updateDeleteNearbyShopsGoods(list);
				if(i==0){
					int a=1/i;
				}
			
		} catch (Exception e) {
			throw new RollBackExecption("外送商品列表 批量下架失败");
		}
		return ApiResult.success();
	}

	/****
	 * 外送商品列表 批量删除
	 * 
	 * @param list
	 * @return
	 * @throws RollBackExecption 
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ApiResult<?> batchDeleteNearbyShopsGoods(List<Map<String, String>>  list) throws RollBackExecption {
		if (list == null || list.size() < 1) {
			return ApiResult.fail("参数非法，批量删除商品Id不能为空");
		}
		try {
			int a=	clyjNearbyShopsGoodsMapper.updateDeleteNearbyShopsGoods(list);
 			if(a==0){
				int b=1/0;
			}
		} catch (Exception e) {
			throw new RollBackExecption("批量删除外送商品信息失败");
		}
		return ApiResult.success();
	}

	/****
	 * 更新外送商品
	 * 
	 * @param clyjNearbyPackageVo
	 * @return
	 * @throws RollBackExecption 
	 * @throws Exception
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ApiResult<?> updateNearbyShopsGoods(ClyjNearbyShopsGoods clyjNearbyShopsGoods,MultipartFile[] goodsPicture) throws RollBackExecption {
		/** 校验 外送商品 请求参数（更新外送商品） **/
		ApiResult<?> r = checkNearbyShopsGoodsParam(clyjNearbyShopsGoods,goodsPicture);
		if (!r.getCode().equals(BaseConstants.SUCCESS)) {
			return r;
		}
		try {
		/** 上传商品图 **/
		Map<String, String> map = uploadPic(goodsPicture);
		if (map.size() < 1) {
			return ApiResult.fail("上传图片失败");
		}
		ClyjNearbyShops clyjNearbyShops = queryClyjNearbyShops();
		if (clyjNearbyShops == null) {
			logger.error("查询店铺失败-----------------参数非法" + "mich_id" + UserUtil.getLoginUser().getUserId());
			return ApiResult.fail("查询店铺失败");
		}
		clyjNearbyShopsGoods.setUpdateTime(LocalDateTime.now());
		int i = clyjNearbyShopsGoodsMapper.updateById(clyjNearbyShopsGoods);
		if(i==0){
			int a =1/i;
		}
		List<ClyjNearbyShopsGoodsSpec> clyjNearbyShopsGoodsSpecList = clyjNearbyShopsGoods
				.getClyjNearbyShopsGoodsSpecList();
		if(clyjNearbyShopsGoodsSpecList!=null && clyjNearbyShopsGoodsSpecList.size()>0){
			for (ClyjNearbyShopsGoodsSpec clyjNearbyShopsGoodsSpec : clyjNearbyShopsGoodsSpecList) {
				if (StringUtils.isEmpty(clyjNearbyShopsGoodsSpec.getSpecId())) {
					return ApiResult.fail("参数非法：" + "id不能为空");
				}
				int j = clyjNearbyShopsGoodsSpecMapper.updateById(clyjNearbyShopsGoodsSpec);
				if(j==0){
					int a =1/j;
				}
			}
		}
		} catch (Exception e) {
			throw new RollBackExecption("更新外送商品");
		}
		return ApiResult.success();
	}

	/****
	 * 保存外送商品
	 * 
	 * @param clyjNearbyPackageVo
	 * @return
	 * @throws RollBackExecption 
	 * @throws Exception
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ApiResult<?> saveNearbyShopsGoods(ClyjNearbyShopsGoods clyjNearbyShopsGoods,MultipartFile[] goodsPicture) throws RollBackExecption {
		/** 校验 外送商品 请求参数（保存外送商品） **/
		ApiResult<?> r = checkNearbyShopsGoodsParam(clyjNearbyShopsGoods,goodsPicture);
		if (!r.getCode().equals(BaseConstants.SUCCESS)) {
			return r;
		}
		if(!clyjNearbyShopsGoods.getType().equals("0")){
			logger.error("保存外送商品-----------------参数非法" + "Type：" + clyjNearbyShopsGoods.getType() );
			return ApiResult.fail("参数非法");
		}
		try {
		/** 上传商品图 **/
		 Map<String,String> map=uploadPic(goodsPicture);
		 if(map.size()<1){
		 return ApiResult.fail("上传图片失败");
		 }
		ClyjNearbyShops clyjNearbyShops = queryClyjNearbyShops();
		if (clyjNearbyShops == null) {
			logger.error("查询店铺失败-----------------参数非法" + "mich_id" + UserUtil.getLoginUser().getUserId());
			return ApiResult.fail("查询店铺失败");
		}
		String goodsId = UUID.randomUUID().toString().replace("-", "");
		clyjNearbyShopsGoods.setGoodsId(goodsId);// 商品id
		clyjNearbyShopsGoods.setShopsId(clyjNearbyShops.getShopsId());// 商铺id
		// 视频TODO
	    clyjNearbyShopsGoods.setPicture(map.get("goodsPictureArrs"));//商品图
		clyjNearbyShopsGoods.setStatus(BaseConstants.PULL_OFF_SHELVES);// 状态（0上架
																		// 1下架）开始保存，默认下架
		clyjNearbyShopsGoods.setAuditingStatus(BaseConstants.AUDITING_STATUS_1); // 审核状态(0,已审核
		clyjNearbyShopsGoods.setDeleteFlg(BaseConstants.DELETE_FLG_0);// 删除标示(0，未删除
																		// 1，删除)
		clyjNearbyShopsGoods.setCreateTime(LocalDateTime.now());
		int i = clyjNearbyShopsGoodsMapper.insert(clyjNearbyShopsGoods);
		if(i==0){
			int a =1/i;
		}
		List<ClyjNearbyShopsGoodsSpec> clyjNearbyShopsGoodsSpecList = clyjNearbyShopsGoods
				.getClyjNearbyShopsGoodsSpecList();
		if(clyjNearbyShopsGoodsSpecList!=null&&clyjNearbyShopsGoodsSpecList.size()>0){
			for (ClyjNearbyShopsGoodsSpec clyjNearbyShopsGoodsSpec : clyjNearbyShopsGoodsSpecList) {
				clyjNearbyShopsGoodsSpec.setSpecId(UUID.randomUUID().toString().replace("-", ""));
				clyjNearbyShopsGoodsSpec.setGoodsId(goodsId);
				int j = clyjNearbyShopsGoodsSpecMapper.insert(clyjNearbyShopsGoodsSpec);
				if(j==0){
					int a =1/j;
				}
			}
		}
		} catch (Exception e) {
			throw new RollBackExecption("保存外送商品失败");
		}
		return ApiResult.success();
	}

	/** 校验请求参数 **/
	private ApiResult<?> checkNearbyShopsGoodsParam(ClyjNearbyShopsGoods clyjNearbyShopsGoods,MultipartFile[] goodsPicture) {
		String goodsName = clyjNearbyShopsGoods.getGoodsName();// 商品名称
		String goodsTypeId = clyjNearbyShopsGoods.getGoodsTypeId();// 商品类型Id
		String goodsSpec=clyjNearbyShopsGoods.getGoodsSpec();//规格（例如，颜色，尺寸）
		String type=clyjNearbyShopsGoods.getType();// 查询类型(0,销售中 ，1未审核 ，2，库存警告 3，仓库中 4.回收站-根据删除标示判断)
		List<ClyjNearbyShopsGoodsSpec> clyjNearbyShopsGoodsSpecList = clyjNearbyShopsGoods.getClyjNearbyShopsGoodsSpecList();
		/**20190430需求变动----如果不设置规格，则只设置一种商品参数（价格，原价（划线价，）佣金，零钱，库存警告，库存**/
		if(clyjNearbyShopsGoodsSpecList==null||clyjNearbyShopsGoodsSpecList.size()<1){
			Integer stock=clyjNearbyShopsGoods.getStock();//库存
			BigDecimal presentPrice=clyjNearbyShopsGoods.getPresentPrice();//商品价格
			if(stock==0||presentPrice.equals(BigDecimal.ZERO)){
				logger.error("商品管理----外送商品校验请求参数" + "stock:" + stock + "---------"
						+ "presentPrice:" + presentPrice + "---------"
						);
				return ApiResult.fail("参数非法");
			}
		}
		MultipartFile[] picture=goodsPicture;//外送商品图(图片)
		if (StringUtils.isEmpty(goodsName) || StringUtils.isEmpty(goodsTypeId)||picture==null|| StringUtils.isEmpty(goodsSpec)||StringUtils.isEmpty(type)) {
			logger.error("商品管理----外送商品校验请求参数" + "goodsName:" + goodsName + "---------"
					+ "goodsTypeId:" + goodsTypeId + "---------"
					+ "picture:" + picture + "---------"
					+ "goodsSpec:" + goodsSpec + "---------"
					+ "type:" + type + "---------"
					);
			return ApiResult.fail("参数非法");
		}
		return ApiResult.success();
	}

	/** 上传图片 **/
	private Map<String, String> uploadPic(MultipartFile[] goodsPicture) {
		Map<String, String> map = new HashMap<>();
		MultipartFile[] goodsPictureArr =goodsPicture;
		StringBuffer sbf = new StringBuffer();
		for (MultipartFile multipartFile : goodsPictureArr) {
			try {
				// 上传文件
				String fileName = multipartFile.getOriginalFilename();
				String pox = fileName.substring(fileName.lastIndexOf(".") + 1);
				InputStream inputStream = multipartFile.getInputStream();
				Map<String, Object> uploadByInputStream = OSSUtils.uploadByInputStream(inputStream, pox,
						"CLYJ/GOODS/SPEC/");
				String goodsPictureArrs = uploadByInputStream.get("path").toString();
				sbf.append(goodsPictureArrs);
			} catch (Exception e) {
				logger.error("商品管理-----外送商品----上传图失败");
			}
			map.put("goodsPictureArrs", sbf.toString());
		}
		return map;
	}

	/** 查询登陆用户店铺 **/
	public ClyjNearbyShops queryClyjNearbyShops() {
		// 查询登录用户角色
		LoginUser loginUser = UserUtil.getLoginUser();
		QueryWrapper<ClyjNearbyShops> queryClyjNearbyShops = new QueryWrapper<ClyjNearbyShops>();
		queryClyjNearbyShops.eq("mich_id", loginUser.getUserId());
		ClyjNearbyShops clyjNearbyShops = clyjNearbyShopsMapper.selectOne(queryClyjNearbyShops);
		return clyjNearbyShops;
	}

	/****
	 * 根据登陆用户查询商品类型
	 * 
	 * @return
	 */
	@Override
	public PageTableResponse queryGoodsType(int start, int length) {
		ClyjNearbyShops clyjNearbyShops = queryClyjNearbyShops();
		if (clyjNearbyShops == null) {
			logger.error("查询店铺失败-----------------参数非法" + "mich_id" + UserUtil.getLoginUser().getUserId());
			return null;
		}
		QueryWrapper<ClyjNearbyGoodsType> queryWrapper = new QueryWrapper<ClyjNearbyGoodsType>();
		queryWrapper.eq("shop_id", clyjNearbyShops.getShopsId());
		/****
		 * // 分页
		Page<ClyjNearbyShopsGoods> page = new Page<ClyjNearbyShopsGoods>(start, length);
		IPage<ClyjNearbyShopsGoods> shopsGoodsIPage = this.clyjNearbyShopsGoodsMapper.selectPage(page, q);
		 */
		Page<ClyjNearbyGoodsType> page = new Page<ClyjNearbyGoodsType>(start, length);
		IPage<ClyjNearbyGoodsType> list = this.clyjNearbyGoodsTypeMapper.selectPage(page, queryWrapper);
		List<ClyjNearbyGoodsType> records = list.getRecords();
		for (ClyjNearbyGoodsType clyjNearbyGoodsType : records) {
			ClyjNearbyGoodsTypeVo g = new ClyjNearbyGoodsTypeVo();
			g.setId(clyjNearbyGoodsType.getId());
			g.setTypeName(clyjNearbyGoodsType.getName());
			g.setShowState(clyjNearbyGoodsType.getShowState());
			g.setTypeSort(clyjNearbyGoodsType.getTypeSort());
			QueryWrapper<ClyjNearbyShopsGoods> queryShopsGoods = new QueryWrapper<ClyjNearbyShopsGoods>();
			queryShopsGoods.eq("goods_type_id", clyjNearbyGoodsType.getId());
			g.setCount(clyjNearbyShopsGoodsMapper.selectCount(queryShopsGoods));
		}
		list.setRecords(records);
		PageTableResponse pageTableResponse = new PageTableResponse(list.getTotal(),
				list.getTotal(), list.getRecords());
		return pageTableResponse;
	}

	/****
	 * 修改商品类型
	 * @param clyjNearbyGoodsTypeVo
	 * @return
	 */
	@Override
	public ApiResult<?> updateGoodsType(ClyjNearbyGoodsTypeVo clyjNearbyGoodsTypeVo) {
		ClyjNearbyShops clyjNearbyShops = queryClyjNearbyShops();
		if (clyjNearbyShops == null) {
			logger.error("查询店铺失败-----------------参数非法" + "mich_id" + UserUtil.getLoginUser().getUserId());
			return ApiResult.fail("查询店铺失败");
		}	
		if(clyjNearbyGoodsTypeVo==null ){
			logger.error("新增商品类型-----------------参数非法" + "clyjNearbyGoodsTypeVo" + clyjNearbyGoodsTypeVo);
			return ApiResult.fail("新增商品类型,参数非法");
		}
		if(StringUtils.isEmpty(clyjNearbyGoodsTypeVo.getTypeName())||StringUtils.isEmpty(clyjNearbyGoodsTypeVo.getTypeSort())|StringUtils.isEmpty(clyjNearbyGoodsTypeVo.getId())){
			logger.error("新增商品类型-----------------参数非法" + "TypeName(" + clyjNearbyGoodsTypeVo.getTypeName()+ "---------"
					+ "TypeSort:" + clyjNearbyGoodsTypeVo.getTypeSort() + "---------"
					+ "Typeid:" + clyjNearbyGoodsTypeVo.getId() + "---------");
			return ApiResult.fail("新增商品类型,参数非法");
		}
		ClyjNearbyGoodsType clyjNearbyGoodsType= new ClyjNearbyGoodsType();
		clyjNearbyGoodsType.setUpdateTime(new Date());
		clyjNearbyGoodsType.setId(clyjNearbyGoodsTypeVo.getId());
		clyjNearbyGoodsType.setName(clyjNearbyGoodsTypeVo.getTypeName());
		clyjNearbyGoodsType.setTypeSort(clyjNearbyGoodsTypeVo.getTypeSort());
		clyjNearbyGoodsType.setShowState(clyjNearbyGoodsTypeVo.getShowState());
		int i=clyjNearbyGoodsTypeMapper.updateById(clyjNearbyGoodsType);
		if(i<1){
			return ApiResult.fail("修改商品类型失败");
		}
		return ApiResult.success();
	}
	/****
	 * 添加商品类型
	 * @param clyjNearbyGoodsTypeVo
	 * @return
	 */
	@Override
	public ApiResult<?> addGoodsType(ClyjNearbyGoodsTypeVo clyjNearbyGoodsTypeVo) {
		ClyjNearbyShops clyjNearbyShops = queryClyjNearbyShops();
		if (clyjNearbyShops == null) {
			logger.error("查询店铺失败-----------------参数非法" + "mich_id" + UserUtil.getLoginUser().getUserId());
			return ApiResult.fail("查询店铺失败");
		}	
		if(clyjNearbyGoodsTypeVo==null ){
			return ApiResult.fail("新增商品类型,参数非法");
		}
		if(StringUtils.isEmpty(clyjNearbyGoodsTypeVo.getTypeName())||StringUtils.isEmpty(clyjNearbyGoodsTypeVo.getTypeSort())){
			return ApiResult.fail("新增商品类型,参数非法");
		}
		ClyjNearbyGoodsType clyjNearbyGoodsType= new ClyjNearbyGoodsType();
		clyjNearbyGoodsType.setCreateTime(new Date());
		clyjNearbyGoodsType.setId(UUID.randomUUID().toString().replace("-", ""));
		clyjNearbyGoodsType.setName(clyjNearbyGoodsTypeVo.getTypeName());
		clyjNearbyGoodsType.setTypeSort(clyjNearbyGoodsTypeVo.getTypeSort());
		clyjNearbyGoodsType.setShowState(BaseConstants.SHOW_STATE_1);
		int i=clyjNearbyGoodsTypeMapper.insert(clyjNearbyGoodsType);
		if(i<1){
			return ApiResult.fail("添加商品类型失败");
		}
		return ApiResult.success();
	}

	/****
	 * 删除商品类型
	 * @param object
	 * @return
	 */
	@Override
	public ApiResult<?> deleteGoodsType(String string) {
		if(StringUtils.isEmpty(string)){
			return ApiResult.fail("删除商品类型,参数非法");
		}
		int a=clyjNearbyGoodsTypeMapper.deleteById(string);
		if(a<1){
			return ApiResult.fail("删除商品类型失败");	
		}
		return ApiResult.success();
	}

	@Override
	public ApiResult<?> batchDeleteGoodsType(List<Map<String, String>> typeIdList) throws RollBackExecption {
		if (typeIdList == null || typeIdList.size() < 1) {
			return ApiResult.fail("参数非法，删除商品类型Id不能为空");
		}
		try {
			int i=	clyjNearbyGoodsTypeMapper.batchDeleteGoodsType(typeIdList);
				if(i==0){
					int a=1/i;
				}
			
		} catch (Exception e) {
			throw new RollBackExecption("外送商品列表 批量下架失败");
		}
		return ApiResult.success();
	}

	@Override
	public ApiResult<?> updateGoodsTypeState(String state, String id) {
		if(StringUtils.isEmpty(state)||StringUtils.isEmpty(id)){
			logger.error("参数非法，修改商品类型状态Id必要参数不能为空"+"state:"+state+"----------"
					+"id:"+id+"----------");
			return ApiResult.fail("参数非法，修改商品类型状态Id必要参数不能为空");
		}
		int a=clyjNearbyGoodsTypeMapper.updateStat(state, id);
		if(a<1){
			return ApiResult.fail("修改商品类型状态失败");	
		}
		return ApiResult.success();
	}
	/****
	 * 上架（ 仓库中：编辑和上架。，（对库存进行参数校验编辑后库存>0进行上架操作））
	 * 查询类型(0,销售中 ，1未审核 ，2，库存警告 3，仓库中 4.回收站-根据删除标示判断)
	 */
	@Override
	public ApiResult<?> putOnsale(String goodsId, String type) {
		if(StringUtils.isEmpty(goodsId)||StringUtils.isEmpty(type)){
			logger.error("团购商品上架操作--参数非法"+"goodsId:"+goodsId+"----------"
					+"type:"+type+"----------");
			return  ApiResult.fail("参数非法");
		}
		if(!type.equals("2")){
			return  ApiResult.fail("当前类型不可执行上架操作");
		}
		ClyjNearbyShopsGoods c=clyjNearbyShopsGoodsMapper.selectById(goodsId);
		if(c==null){
			return  ApiResult.fail("未查询到团购商品");
		}
		if(c.getStock()<1){
			return  ApiResult.fail("库存不足不可以上架");
		}
		int i=clyjNearbyShopsGoodsMapper.putOnsale(goodsId);
		if(i<1){
			return  ApiResult.fail("上架失敗");
		}
		return ApiResult.success();
	}

}
